using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using JGSY.CMS.LowCode.Platform.Application.DTOs;
using JGSY.CMS.LowCode.Platform.Application.Interfaces;
using JGSY.CMS.LowCode.Platform.Domain.Entities;
using JGSY.CMS.LowCode.Platform.Domain.Interfaces;

namespace JGSY.CMS.LowCode.Platform.Application.Services
{
    /// <summary>
    /// 团队应用服务实现
    /// 提供团队管理的完整业务逻辑，包括团队CRUD操作、成员管理、权限控制等功能
    /// </summary>
    /// <remarks>
    /// 该服务负责处理团队相关的所有业务操作：
    /// - 团队的创建、查询、更新、删除
    /// - 团队成员的添加、移除、角色管理
    /// - 批量操作支持
    /// - 团队权限验证和状态管理
    /// </remarks>
    public class TeamAppService : ITeamAppService
    {
        private readonly ITeamRepository _teamRepository;
        private readonly ITeamMemberRepository _teamMemberRepository;
        private readonly ILogger<TeamAppService> _logger;

        /// <summary>
        /// 初始化团队应用服务
        /// </summary>
        /// <param name="teamRepository">团队数据仓储接口</param>
        /// <param name="teamMemberRepository">团队成员数据仓储接口</param>
        /// <param name="logger">日志记录器</param>
        /// <exception cref="ArgumentNullException">当任何参数为null时抛出</exception>
        public TeamAppService(
            ITeamRepository teamRepository,
            ITeamMemberRepository teamMemberRepository,
            ILogger<TeamAppService> logger)
        {
            _teamRepository = teamRepository ?? throw new ArgumentNullException(nameof(teamRepository));
            _teamMemberRepository = teamMemberRepository ?? throw new ArgumentNullException(nameof(teamMemberRepository));
            _logger = logger ?? throw new ArgumentNullException(nameof(logger));
        }

        /// <summary>
        /// 向团队添加成员
        /// </summary>
        /// <param name="teamId">团队标识符</param>
        /// <param name="userId">用户标识符</param>
        /// <param name="role">成员角色，可选参数，默认为"member"</param>
        /// <returns>添加成功返回true，失败或已存在返回false</returns>
        /// <exception cref="Exception">数据库操作异常</exception>
        /// <remarks>
        /// 添加成员前会验证：
        /// 1. 团队是否存在
        /// 2. 用户是否已是团队成员
        /// 如果用户已是团队成员，则不会重复添加
        /// </remarks>
        public async Task<bool> AddMemberAsync(long teamId, long userId, string? role = null)
        {
            try
            {
                _logger.LogInformation("开始向团队 {TeamId} 添加成员 {UserId}，角色: {Role}", teamId, userId, role ?? "member");

                var team = await _teamRepository.GetByIdAsync(teamId);
                if (team == null)
                {
                    _logger.LogWarning("团队不存在: {TeamId}", teamId);
                    return false;
                }

                var isMember = await _teamMemberRepository.IsMemberAsync(teamId, userId);
                if (isMember)
                {
                    _logger.LogInformation("用户 {UserId} 已是团队 {TeamId} 的成员", userId, teamId);
                    return false; // 已经是成员
                }

                var teamMember = new TeamMember
                {
                    TeamId = teamId,
                    UserId = userId,
                    Role = role ?? "member",
                    JoinedAt = DateTime.UtcNow
                };

                await _teamMemberRepository.AddAsync(teamMember);
                _logger.LogInformation("成功将用户 {UserId} 添加到团队 {TeamId}，角色: {Role}", userId, teamId, role ?? "member");
                return true;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "向团队添加成员失败: 团队ID {TeamId}, 用户ID {UserId}", teamId, userId);
                throw;
            }
        }

        /// <summary>
        /// 批量向团队添加成员
        /// </summary>
        /// <param name="teamId">团队标识符</param>
        /// <param name="userIds">用户标识符集合</param>
        /// <param name="role">成员角色，可选参数，默认为"member"</param>
        /// <returns>成功添加的成员数量</returns>
        /// <exception cref="Exception">数据库操作异常</exception>
        /// <remarks>
        /// 批量添加操作会逐个处理每个用户：
        /// - 跳过已存在的成员
        /// - 跳过无效的用户ID
        /// - 返回实际成功添加的数量
        /// </remarks>
        public async Task<int> BatchAddMembersAsync(long teamId, IEnumerable<long> userIds, string? role = null)
        {
            try
            {
                _logger.LogInformation("开始批量向团队 {TeamId} 添加成员，数量: {Count}", teamId, userIds.Count());

                var addedCount = 0;
                foreach (var userId in userIds)
                {
                    var success = await AddMemberAsync(teamId, userId, role);
                    if (success)
                    {
                        addedCount++;
                    }
                }

                _logger.LogInformation("批量添加成员完成，团队 {TeamId} 成功添加 {AddedCount} 名成员", teamId, addedCount);
                return addedCount;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "批量添加团队成员失败: 团队ID {TeamId}", teamId);
                throw;
            }
        }

        /// <summary>
        /// 批量删除团队
        /// </summary>
        /// <param name="ids">团队标识符集合</param>
        /// <returns>成功删除的团队数量</returns>
        /// <exception cref="Exception">数据库操作异常</exception>
        /// <remarks>
        /// 批量删除操作会逐个处理每个团队：
        /// - 跳过不存在的团队
        /// - 处理删除过程中的关联数据清理
        /// - 返回实际成功删除的数量
        /// </remarks>
        public async Task<int> BatchDeleteAsync(IEnumerable<long> ids)
        {
            try
            {
                _logger.LogInformation("开始批量删除团队，数量: {Count}", ids.Count());

                var deletedCount = 0;
                foreach (var id in ids)
                {
                    var success = await DeleteAsync(id);
                    if (success)
                    {
                        deletedCount++;
                    }
                }

                _logger.LogInformation("批量删除团队完成，成功删除 {DeletedCount} 个团队", deletedCount);
                return deletedCount;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "批量删除团队失败");
                throw;
            }
        }

        /// <summary>
        /// 批量从团队移除成员
        /// </summary>
        /// <param name="teamId">团队标识符</param>
        /// <param name="userIds">要移除的用户标识符集合</param>
        /// <returns>成功移除的成员数量</returns>
        /// <exception cref="Exception">数据库操作异常</exception>
        /// <remarks>
        /// 批量移除操作会逐个处理每个用户：
        /// - 跳过不是团队成员的用户
        /// - 处理移除过程中的关联数据清理
        /// - 返回实际成功移除的数量
        /// </remarks>
        public async Task<int> BatchRemoveMembersAsync(long teamId, IEnumerable<long> userIds)
        {
            try
            {
                _logger.LogInformation("开始批量从团队 {TeamId} 移除成员，数量: {Count}", teamId, userIds.Count());

                var removedCount = 0;
                foreach (var userId in userIds)
                {
                    var success = await RemoveMemberAsync(teamId, userId);
                    if (success)
                    {
                        removedCount++;
                    }
                }

                _logger.LogInformation("批量移除成员完成，从团队 {TeamId} 成功移除 {RemovedCount} 名成员", teamId, removedCount);
                return removedCount;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "批量移除团队成员失败: 团队ID {TeamId}", teamId);
                throw;
            }
        }

        /// <summary>
        /// 检查团队是否可以删除
        /// </summary>
        /// <param name="id">团队标识符</param>
        /// <returns>可以删除返回true，否则返回false</returns>
        /// <exception cref="Exception">数据库查询异常时返回false</exception>
        /// <remarks>
        /// 删除条件验证：
        /// - 团队没有活跃成员时才可以删除
        /// - 异常情况下默认返回false，确保数据安全
        /// </remarks>
        public async Task<bool> CanDeleteAsync(long id)
        {
            try
            {
                _logger.LogInformation("检查团队是否可以删除: {TeamId}", id);

                var memberCount = await _teamRepository.GetMemberCountAsync(id);
                var canDelete = memberCount == 0;
                
                _logger.LogInformation("团队 {TeamId} 删除检查结果: {CanDelete}，成员数量: {MemberCount}", id, canDelete, memberCount);
                return canDelete;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "检查团队是否可删除失败: 团队ID {TeamId}", id);
                return false;
            }
        }

        /// <summary>
        /// 检查团队代码是否已存在
        /// </summary>
        /// <param name="code">团队代码</param>
        /// <param name="excludeId">排除的团队ID（用于更新时的重复检查）</param>
        /// <returns>代码已存在返回true，否则返回false</returns>
        /// <exception cref="Exception">数据库查询异常</exception>
        /// <remarks>
        /// 代码唯一性验证：
        /// - 检查指定代码是否已被其他团队使用
        /// - excludeId参数用于更新操作时排除当前团队
        /// </remarks>
        public async Task<bool> CodeExistsAsync(string code, long? excludeId = null)
        {
            try
            {
                _logger.LogInformation("检查团队代码是否存在: {Code}，排除ID: {ExcludeId}", code, excludeId);

                var teams = await _teamRepository.FindAsync(t => 
                    t.Code == code && (!excludeId.HasValue || t.Id != excludeId.Value));
                var exists = teams.Any();

                _logger.LogInformation("团队代码 {Code} 存在性检查结果: {Exists}", code, exists);
                return exists;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "检查团队代码是否存在失败: {Code}", code);
                throw;
            }
        }

        /// <summary>
        /// 创建新团队
        /// </summary>
        /// <param name="teamDto">团队数据传输对象</param>
        /// <returns>创建成功的团队信息</returns>
        /// <exception cref="ArgumentNullException">teamDto为null时抛出</exception>
        /// <exception cref="Exception">数据库操作异常</exception>
        /// <remarks>
        /// 创建团队流程：
        /// 1. 验证输入数据的完整性
        /// 2. 创建团队实体并设置基础信息
        /// 3. 保存到数据库
        /// 4. 返回创建后的团队信息
        /// </remarks>
        public async Task<TeamDto> CreateAsync(TeamDto teamDto)
        {
            if (teamDto == null) throw new ArgumentNullException(nameof(teamDto));

            try
            {
                _logger.LogInformation("开始创建团队: {TeamName}，代码: {Code}", teamDto.Name, teamDto.Code);

                var team = new Team
                {
                    Name = teamDto.Name,
                    Code = teamDto.Code,
                    Description = teamDto.Description,
                    LeaderId = teamDto.LeaderId,
                    DepartmentId = teamDto.DepartmentId,
                    Type = teamDto.TeamType,
                    MaxMembers = teamDto.MaxMembers,
                    SortOrder = teamDto.SortOrder,
                    Status = teamDto.Status,
                    CreatedBy = teamDto.CreatedBy,
                    EstablishedAt = DateTime.UtcNow,
                    CreatedAt = DateTime.UtcNow,
                    UpdatedAt = DateTime.UtcNow
                };

                await _teamRepository.AddAsync(team);
                _logger.LogInformation("团队创建成功: {TeamName} (ID: {TeamId})", team.Name, team.Id);
                
                return MapToDto(team);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "创建团队失败: {TeamName}", teamDto.Name);
                throw;
            }
        }

        /// <summary>
        /// 删除团队
        /// </summary>
        /// <param name="id">团队标识符</param>
        /// <returns>删除成功返回true，失败或团队不存在返回false</returns>
        /// <exception cref="Exception">数据库操作异常</exception>
        /// <remarks>
        /// 删除团队前的安全检查：
        /// 1. 验证团队是否存在
        /// 2. 检查是否有活跃成员
        /// 3. 只有没有活跃成员的团队才能被删除
        /// </remarks>
        public async Task<bool> DeleteAsync(long id)
        {
            try
            {
                _logger.LogInformation("开始删除团队: {TeamId}", id);

                var team = await _teamRepository.GetByIdAsync(id);
                if (team == null)
                {
                    _logger.LogWarning("要删除的团队不存在: {TeamId}", id);
                    return false;
                }

                // 检查是否可以删除（没有活跃成员）
                var canDelete = await CanDeleteAsync(id);
                if (!canDelete)
                {
                    _logger.LogWarning("无法删除团队 {TeamId} - 存在活跃成员", id);
                    return false;
                }

                await _teamRepository.DeleteAsync(id);
                _logger.LogInformation("团队删除成功: {TeamId}", id);
                return true;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "删除团队失败: {TeamId}", id);
                return false;
            }
        }

        /// <summary>
        /// 获取所有团队列表
        /// </summary>
        /// <returns>团队信息集合</returns>
        /// <exception cref="Exception">数据库查询异常</exception>
        /// <remarks>
        /// 返回系统中所有团队的完整信息列表，
        /// 包括团队基础信息、成员统计等数据
        /// </remarks>
        public async Task<IEnumerable<TeamDto>> GetAllAsync()
        {
            try
            {
                _logger.LogInformation("获取所有团队列表");

                var teams = await _teamRepository.GetAllAsync();
                var teamDtos = teams.Select(MapToDto).ToList();

                _logger.LogInformation("成功获取团队列表，数量: {Count}", teamDtos.Count);
                return teamDtos;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取所有团队失败");
                throw;
            }
        }

        /// <summary>
        /// 根据团队代码获取团队信息
        /// </summary>
        /// <param name="code">团队代码</param>
        /// <returns>团队信息，不存在时返回null</returns>
        /// <exception cref="Exception">数据库查询异常</exception>
        /// <remarks>
        /// 通过唯一的团队代码查找团队信息，
        /// 常用于代码验证和快速定位团队
        /// </remarks>
        public async Task<TeamDto?> GetByCodeAsync(string code)
        {
            try
            {
                _logger.LogInformation("根据代码获取团队: {Code}", code);

                var teams = await _teamRepository.FindAsync(t => t.Code == code);
                var team = teams.FirstOrDefault();
                var result = team == null ? null : MapToDto(team);

                _logger.LogInformation("根据代码 {Code} 查找团队结果: {Found}", code, result != null);
                return result;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "根据代码获取团队失败: {Code}", code);
                throw;
            }
        }

        public async Task<IEnumerable<TeamDto>> GetByDepartmentAsync(long departmentId)
        {
            try
            {
                var teams = await _teamRepository.FindAsync(t => t.DepartmentId == departmentId);
                return teams.Select(MapToDto).ToList();
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error getting teams by department: {DepartmentId}", departmentId);
                throw;
            }
        }

        public async Task<TeamDto?> GetByIdAsync(long id)
        {
            try
            {
                var team = await _teamRepository.GetByIdAsync(id);
                return team == null ? null : MapToDto(team);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error getting team by ID: {TeamId}", id);
                throw;
            }
        }

        public async Task<(IEnumerable<TeamDto> Items, int TotalCount)> GetPagedAsync(int pageIndex, int pageSize, string? keyword = null, long? departmentId = null, string? teamType = null, byte? status = null)
        {
            try
            {
                var (items, totalCount) = await _teamRepository.GetPagedAsync(pageIndex, pageSize, t => 
                    (string.IsNullOrEmpty(keyword) || t.Name.Contains(keyword) || (t.Code != null && t.Code.Contains(keyword))) &&
                    (!departmentId.HasValue || t.DepartmentId == departmentId) &&
                    (string.IsNullOrEmpty(teamType) || t.Type == teamType) &&
                    (!status.HasValue || t.Status == status));

                var dtos = items.Select(MapToDto).ToList();
                return (dtos, totalCount);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error getting paged teams");
                throw;
            }
        }

        public async Task<IEnumerable<UserDto>> GetTeamMembersAsync(long teamId, bool activeOnly = true)
        {
            try
            {
                var members = await _teamMemberRepository.GetByTeamIdAsync(teamId);
                if (activeOnly)
                {
                    members = members.Where(m => m.Status == 1).ToList();
                }

                // 这里需要将TeamMember转换为UserDto，但需要加载User信息
                // 简化实现，返回空列表，在实际项目中需要Join User表
                var userDtos = new List<UserDto>();
                foreach (var member in members)
                {
                    // 这里应该根据member.UserId获取用户信息并转换为UserDto
                    // 暂时跳过具体实现
                }

                return userDtos;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error getting team members: {TeamId}", teamId);
                throw;
            }
        }

        public async Task<object> GetTeamPerformanceAsync(long id, DateTime? startDate = null, DateTime? endDate = null)
        {
            try
            {
                var team = await _teamRepository.GetByIdAsync(id);
                if (team == null)
                    return new { };

                // 设置默认日期范围
                var start = startDate ?? DateTime.UtcNow.AddDays(-30);
                var end = endDate ?? DateTime.UtcNow;

                var members = await _teamMemberRepository.GetByTeamIdAsync(id);
                var memberCount = members.Count(m => m.Status == 1);

                // 简化的性能指标，在实际项目中可以从其他表获取更详细的数据
                return new
                {
                    TeamId = id,
                    TeamName = team.Name,
                    Period = new
                    {
                        StartDate = start,
                        EndDate = end,
                        Days = (end - start).Days
                    },
                    Performance = new
                    {
                        ActiveMembers = memberCount,
                        ProductivityScore = CalculateProductivityScore(memberCount),
                        CollaborationIndex = CalculateCollaborationIndex(memberCount),
                        EfficiencyRating = CalculateEfficiencyRating(team.Status, memberCount)
                    },
                    Summary = new
                    {
                        OverallRating = "Good", // 简化实现
                        Recommendations = GenerateRecommendations(memberCount, team.Status)
                    }
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error getting team performance: {TeamId}", id);
                throw;
            }
        }

        private static double CalculateProductivityScore(int memberCount)
        {
            // 简化的生产力计算逻辑
            return Math.Min(100, memberCount * 15 + 25);
        }

        private static double CalculateCollaborationIndex(int memberCount)
        {
            // 简化的协作指数计算
            return memberCount > 1 ? Math.Min(100, memberCount * 12 + 30) : 0;
        }

        private static string CalculateEfficiencyRating(byte status, int memberCount)
        {
            if (status == 0) return "Disbanded";
            if (memberCount == 0) return "Low";
            if (memberCount <= 3) return "Good";
            if (memberCount <= 8) return "High";
            return "Excellent";
        }

        private static List<string> GenerateRecommendations(int memberCount, byte status)
        {
            var recommendations = new List<string>();
            
            if (status == 0)
                recommendations.Add("团队已解散，考虑重新激活");
            else if (memberCount == 0)
                recommendations.Add("团队没有成员，需要添加成员");
            else if (memberCount == 1)
                recommendations.Add("考虑增加团队成员以提高协作效果");
            else if (memberCount > 10)
                recommendations.Add("团队规模较大，可以考虑拆分为子团队");
            else
                recommendations.Add("团队规模合适，保持当前状态");

            return recommendations;
        }

        public async Task<object> GetTeamStatisticsAsync(long id)
        {
            try
            {
                var team = await _teamRepository.GetByIdAsync(id);
                if (team == null)
                    return new { };

                var memberCount = await _teamRepository.GetMemberCountAsync(id);
                var members = await _teamMemberRepository.GetByTeamIdAsync(id);
                
                var activeMemberCount = members.Count(m => m.Status == 1);
                var inactiveMemberCount = members.Count(m => m.Status != 1);

                return new
                {
                    TeamId = id,
                    TeamName = team.Name,
                    TotalMembers = memberCount,
                    ActiveMembers = activeMemberCount,
                    InactiveMembers = inactiveMemberCount,
                    TeamStatus = team.Status,
                    EstablishedAt = team.EstablishedAt,
                    LastUpdated = team.UpdatedAt,
                    LeaderInfo = team.LeaderId.HasValue ? new { Id = team.LeaderId.Value } : null
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error getting team statistics: {TeamId}", id);
                throw;
            }
        }

        public async Task<IEnumerable<TeamDto>> GetUserTeamsAsync(long userId)
        {
            try
            {
                var teams = await _teamRepository.GetUserTeamsAsync(userId);
                return teams.Select(MapToDto).ToList();
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error getting user teams: {UserId}", userId);
                throw;
            }
        }

        public async Task<bool> IsMemberAsync(long teamId, long userId)
        {
            try
            {
                return await _teamMemberRepository.IsMemberAsync(teamId, userId);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error checking if user is team member: TeamId={TeamId}, UserId={UserId}", teamId, userId);
                throw;
            }
        }

        public async Task<bool> RemoveMemberAsync(long teamId, long userId)
        {
            try
            {
                var isMember = await _teamMemberRepository.IsMemberAsync(teamId, userId);
                if (!isMember)
                    return false;

                var members = await _teamMemberRepository.FindAsync(m => m.TeamId == teamId && m.UserId == userId);
                var member = members.FirstOrDefault();
                if (member != null)
                {
                    await _teamMemberRepository.DeleteAsync(member);
                }

                _logger.LogInformation("User {UserId} removed from team {TeamId}", userId, teamId);
                return true;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error removing member from team: TeamId={TeamId}, UserId={UserId}", teamId, userId);
                throw;
            }
        }

        public async Task<(IEnumerable<TeamDto> Items, int TotalCount)> SearchAsync(string keyword, int pageIndex = 1, int pageSize = 20)
        {
            try
            {
                return await GetPagedAsync(pageIndex, pageSize, keyword);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error searching teams with keyword: {Keyword}", keyword);
                throw;
            }
        }

        public async Task<bool> SetLeaderAsync(long id, long? leaderId)
        {
            try
            {
                var team = await _teamRepository.GetByIdAsync(id);
                if (team == null)
                    return false;

                team.LeaderId = leaderId;
                team.UpdatedAt = DateTime.UtcNow;
                await _teamRepository.UpdateAsync(team);

                _logger.LogInformation("Team leader updated: TeamId={TeamId}, LeaderId={LeaderId}", id, leaderId);
                return true;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error setting team leader: TeamId={TeamId}, LeaderId={LeaderId}", id, leaderId);
                return false;
            }
        }

        public async Task<bool> TransferToDepartmentAsync(long id, long newDepartmentId)
        {
            try
            {
                var team = await _teamRepository.GetByIdAsync(id);
                if (team == null)
                    return false;

                team.DepartmentId = newDepartmentId;
                team.UpdatedAt = DateTime.UtcNow;
                await _teamRepository.UpdateAsync(team);

                _logger.LogInformation("Team transferred to department: TeamId={TeamId}, DepartmentId={DepartmentId}", id, newDepartmentId);
                return true;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error transferring team to department: TeamId={TeamId}, DepartmentId={DepartmentId}", id, newDepartmentId);
                return false;
            }
        }

        public async Task<TeamDto> UpdateAsync(TeamDto teamDto)
        {
            try
            {
                var team = await _teamRepository.GetByIdAsync(teamDto.Id);
                if (team == null)
                    throw new ArgumentException($"Team with ID {teamDto.Id} not found");

                // 更新团队属性
                team.Name = teamDto.Name;
                team.Code = teamDto.Code;
                team.Description = teamDto.Description;
                team.LeaderId = teamDto.LeaderId;
                team.DepartmentId = teamDto.DepartmentId == 0 ? null : teamDto.DepartmentId;
                team.Type = teamDto.TeamType;
                team.MaxMembers = teamDto.MaxMembers;
                team.SortOrder = teamDto.SortOrder;
                team.Status = teamDto.Status;
                team.UpdatedAt = DateTime.UtcNow;

                await _teamRepository.UpdateAsync(team);
                _logger.LogInformation("Team updated: {TeamName} (ID: {TeamId})", team.Name, team.Id);
                
                return MapToDto(team);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error updating team: {TeamId}", teamDto.Id);
                throw;
            }
        }

        public async Task<bool> UpdateMemberRoleAsync(long teamId, long userId, string role)
        {
            try
            {
                var members = await _teamMemberRepository.FindAsync(m => m.TeamId == teamId && m.UserId == userId);
                var member = members.FirstOrDefault();
                if (member == null)
                    return false;

                member.Role = role;
                await _teamMemberRepository.UpdateAsync(member);

                _logger.LogInformation("Team member role updated: TeamId={TeamId}, UserId={UserId}, Role={Role}", teamId, userId, role);
                return true;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error updating member role: TeamId={TeamId}, UserId={UserId}", teamId, userId);
                return false;
            }
        }

        public async Task<bool> UpdateStatusAsync(long id, byte status)
        {
            try
            {
                var team = await _teamRepository.GetByIdAsync(id);
                if (team == null)
                    return false;

                team.Status = status;
                team.UpdatedAt = DateTime.UtcNow;
                
                // 如果状态是解散(0)，设置解散时间
                if (status == 0)
                {
                    team.DisbandedAt = DateTime.UtcNow;
                }

                await _teamRepository.UpdateAsync(team);

                _logger.LogInformation("Team status updated: TeamId={TeamId}, Status={Status}", id, status);
                return true;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error updating team status: TeamId={TeamId}", id);
                return false;
            }
        }

        // 私有辅助方法
        private TeamDto MapToDto(Team team)
        {
            return new TeamDto
            {
                Id = team.Id,
                Name = team.Name,
                Code = team.Code,
                Description = team.Description,
                LeaderId = team.LeaderId,
                DepartmentId = team.DepartmentId ?? 0,
                TeamType = team.Type,
                SortOrder = team.SortOrder,
                Status = team.Status,
                CreatedBy = team.CreatedBy ?? 0,
                CreatedAt = team.CreatedAt,
                UpdatedAt = team.UpdatedAt,
                LeaderName = team.Leader?.RealName ?? team.Leader?.Username,
                DepartmentName = team.Department?.Name,
                MemberCount = team.TeamMembers?.Count ?? 0,
                ActiveMemberCount = team.TeamMembers?.Count(m => m.Status == 1) ?? 0
            };
        }
    }
}
